#coding=utf-8
from uliweb import expose
from uliweb.orm import get_model,Begin,Commit,Rollback


def __begin__():
    """
    用户验证 权限验证
    """
    from uliweb import functions
    functions.require_login()
    return functions.has_role()

@expose('/myrbac')
class MyRbac(object):
    def __init__(self):
        self.usermodel = get_model('user')
        self.menumodel = get_model('menu')
        self.menurolemodel = get_model('menurole')

    def __begin__(self):
        if not request.user.is_superuser:
            error('你不是超级用户不能进行这项操作！')


    def myrole(self):
        """
        操作角色
        """
        return {}

    def myroleadd(self):
        """
        添加操作角色
        """
        data = []
    
        #列出非管理员用户的非锁定账户
        ormdata = self.usermodel.filter(self.usermodel.c.is_superuser == 0).filter(self.usermodel.c.locked == 0).filter().fields('id','nickname')
    
        for i in ormdata:
            select_data =  '<option value="' + str(i.id) + '">' + i.nickname + '</option>'
            data.append(select_data)
    
        return {"html_user":"".join(data)}

    def myroleedit(self):
        """
        编辑操作角色
        """
        _id = request.GET.get("id")
        #如果_id不存在，就是url非法输入，就提示错误
        if _id == None or _id == "":
            return json({"status":500,"msg":"URL错误"})
        
        #从redis获取数据
        ormdata = functions.get_object(self.menurolemodel, _id, cache=True, use_local=True)
        
        data = []
        #查找出非管理员的用户
        ormdata_user = self.usermodel.filter(self.usermodel.c.is_superuser == 0).filter(self.usermodel.c.locked == 0).filter().fields('id','nickname')
        
        for i in ormdata_user:
            if i.id in ormdata.users.ids():
                select_data =  '<option value="' + str(i.id) + '" selected>' + i.nickname + '</option>'
            else:
                select_data =  '<option value="' + str(i.id) + '">' + i.nickname + '</option>'
            data.append(select_data)


        #将对象传给模版
        return {"ormdata":ormdata,"html_user":"".join(data)}  

    def myrolesave(self):
        """
        保存菜单权限
        """
        _id = request.POST.get('id')
        name = request.POST.get('name')
        description = request.POST.get('description')

        #格式1,2,3
        menusid = request.POST.get('menusid')
        #非序列话的操作
        users = request.POST.getlist('users[]')
        
        if menusid == None:
            return json({"error":500,"msg":"菜单权限不能为空"})

        #将菜单格式化进list
        menu_ids = []
        for i in menusid.split(","):
            menu_ids.append(i)
            
            
        #用于标识是新增还是修改.默认新增True
        flag=True
        
        if _id == None:
            ormdata = self.menurolemodel(name=name,
                                      description=description
                                      )

        else:
            flag = False
            ormdata = functions.get_object(self.menurolemodel, int(_id), cache=True, use_local=True)
            #update操作
            ormdata.name=name
            ormdata.description=description

        Begin()

        try:
            ormdata.save()

            #多对多操作
            ormdata_user = list(self.usermodel.filter(self.usermodel.c.id.in_(users)).filter().fields('id'))
            ormdata_menu = list(self.menumodel.filter(self.menumodel.c.id.in_(menu_ids)).filter().fields('id'))
        
            if flag:
                ormdata.users.add(ormdata_user)
                ormdata.menus.add(ormdata_menu)
            else:
                ormdata.users.update(ormdata_user)
                ormdata.menus.update(ormdata_menu)
                
            Commit()
            return json({"status":200,"msg":"添加成功"}) 

        except:
            Rollback()
            return json({"error":500,"msg":"保存失败"})

    def myroledel(self):
        """
        删除菜单权限
        """
    
        _id = request.GET.get('id')
    
        #通过id，获取权限信息
        menurole = self.menurolemodel.get(int(_id))
        #获取所有菜单id
        menusid = menurole.menus.ids()
        #获取所有用户id
        usersid = menurole.users.ids()

        menurole.users.remove(usersid)
        menurole.menus.remove(menusid)
    
        menurole.delete()
    
        #self.menumenurolemodel.filter(self.menumenurolemodel.c.id.in_(mid)).remove()
        return json({"success":True,"msg":"删除成功"})
    
    def myroledellist(self):
        """
        批量删除菜单权限
        """
    
        _id = request.POST.get('id')
            
        for i in _id.split(','):

            #通过id，获取权限信息
            menurole = self.menurolemodel.get(int(i))
            #获取所有菜单id
            menusid = menurole.menus.ids()
            #获取所有用户id
            usersid = menurole.users.ids()
            
            menurole.users.remove(usersid)
            menurole.menus.remove(menusid)
        
            menurole.delete()
    
        #self.menumenurolemodel.filter(self.menumenurolemodel.c.id.in_(mid)).remove()
        return json({"success":True,"msg":"删除成功"})